package com.intel.factorytest;

import java.io.IOException;
import java.util.List;
import java.util.Locale;
import java.util.Map;

import com.intel.factorytest.application.MATApplication;
import com.intel.factorytest.cfparser.ConfigFileParseUtil;
import com.intel.factorytest.cfparser.concrete.AConfigFileParser;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Color;
import android.media.AudioManager;
import android.os.Bundle;
import android.text.Spannable;
import android.text.SpannableStringBuilder;
import android.text.style.CharacterStyle;
import android.text.style.ForegroundColorSpan;
import android.util.Log;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

public class FactoryTestResultShow extends Activity implements
        View.OnClickListener {
    private static final String TAG = "FactoryTestResultShow";

    private String test_type = "FACTORY_TEST_TYPE";
    private String sdcard_config = "SDCARD_CONFIG";

    private Button mReportButton;
    private Button mBackButton;
    private TextView mTestResultShow;
    private SpannableStringBuilder mSpanString;
    private List<Map<String, Object>> testMenuItems = null;

    private String sdFilePath = "";

    private int mTestType;
    private int is_sys = 0;
    private int is_sys_for_pcba = 0;

    private DatabaseHelper mHelper = null;

    private CharacterStyle mSpanTextColor;
    private int mTextColor;
    private ResultDataSave mTestResultData;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
                WindowManager.LayoutParams.FLAG_FULLSCREEN);

        int is_sys = 0;
        int is_sys_for_pcba = 0;
        updateConfiguration();
        setTitle(R.string.factorytest_single_result);

        mHelper = new DatabaseHelper(this);
        mSpanString = new SpannableStringBuilder();
        setContentView(R.layout.factorytest_result_show);
        mTestResultShow = (TextView) findViewById(R.id.result);
        mReportButton = (Button) findViewById(R.id.button_report);
        mReportButton.setOnClickListener(this);
        mBackButton = (Button) findViewById(R.id.button_reback);
        mBackButton.setOnClickListener(this);

        Intent mIntent = getIntent();
        mTestType = mIntent.getIntExtra(test_type, 0);
        mTestType = ResultDataSave.SYSTEM_ITEM_TEST;// galen
        if (mTestType == ResultDataSave.SYSTEM_ITEM_TEST) {
            is_sys = 1;
            is_sys_for_pcba = 0;
        } else if (mTestType == ResultDataSave.PCB_ITEM_TEST) {
            is_sys = 1;
            is_sys_for_pcba = 1;
        } else {
            is_sys = 0;
            is_sys_for_pcba = 0;
        }
        sdFilePath = mIntent.getStringExtra(sdcard_config);

        Configuration conf = getResources().getConfiguration();
        String localeString = conf.locale.getCountry();

        testMenuItems = ConfigFileParseUtil.getConfParserConcrete(this,
                AConfigFileParser.EXTENSION_PROPERTISE).doParse(is_sys,
                is_sys_for_pcba, localeString, sdFilePath);

        // if (is_sys==0){
        // mTestResultData = new ResultDataSave();
        // mTestResultData.initResultData(this, mTestType, testMenuItems);
        // }

        // queryData(mtestType);
        mTestResultData = new ResultDataSave();
        boolean init;
        init = mTestResultData.initResultData(this, mTestType, testMenuItems);
        Log.d(TAG, "init:" + init);
        Map map;
        int mResult;
        String username;
        String mResultString;
        String mRowShow;
        int mStartSpan;
        // for (int i = 0; i < testMenuItems.size(); i++) {
        for (int i = 0; i < testMenuItems.size(); i++) {
            map = (Map) testMenuItems.get(i);
            username = (String) map.get("itemName");
            // if (is_sys==1){
            // mResult = QueryByName(mTestType, username);
            // }else{
            // mResult =ReadResultByName(mTestType, username);
            // }
            // mResult = QueryByName(mTestType, username);

            mResult = mTestResultData.getDataOfList(mTestType, username);

            if (mResult == ResultDataSave.ITEM_TEST_SUCCES) {
                mResultString = getString(R.string.factorytest_result_succes);
                mTextColor = Color.GREEN;
            } else if (mResult == ResultDataSave.ITEM_TEST_FAIL) {
                mResultString = getString(R.string.factorytest_result_fail);
                mTextColor = Color.RED;
            } else {
                mResultString = getString(R.string.factorytest_result_notest);
//                mTextColor = Color.YELLOW;
                mTextColor = Color.BLACK;
            }
            // mRowShow = Integer.toString(i + 1) + "  " + username;
            // for (int j = 0; j < (30 - mRowShow.length()); j++) {
            // mRowShow += "   ";
            // }
            // mRowShow += mResultString + "\n";
            mRowShow = Integer.toString(i + 1) + "      ";
            if (i < 9) {
                mRowShow += "  ";
            }
            mRowShow += mResultString + "         " + username + "\n";
            mSpanTextColor = new ForegroundColorSpan(mTextColor);
            mSpanString.append(mRowShow);
            mStartSpan = mSpanString.length() - mRowShow.length();
            Log.d(TAG, "mRowShow.length():" + mRowShow.length()
                    + "  mSpanString.length():" + mSpanString.length());
            mSpanString.setSpan(mSpanTextColor, mStartSpan,
                    mSpanString.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        }

         mTestResultShow.setText(mSpanString);
        // mTestResultData.SaveResultData(this, mTestType,
        // testMenuItems);
        // try {
        // mTestResultData.SaveResultToFile(mTestType);
        // } catch (IOException e) {
        // // TODO Auto-generated catch block
        // e.printStackTrace();
        // }
    }

    @Override
    protected void onResume() {
        // TODO Auto-generated method stub
        super.onResume();
        mTestResultData.SaveResultData(this, mTestType, testMenuItems);
//        try {
//            mTestResultData.SaveResultToFile(mTestType);
//        } catch (IOException e) {
//            // TODO Auto-generated catch block
//            e.printStackTrace();
//        }
    }

    @Override
    protected void onPause() {
        // TODO Auto-generated method stub
        super.onPause();
    }

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        Resources resourse = this.getResources();
        Configuration config = resourse.getConfiguration();
        SharedPreferences pre = getSharedPreferences(
                MATApplication.LANGUAGE_PREF, Context.MODE_PRIVATE);
        String lanPre = pre.getString(MATApplication.LANGUAGE_KEY, "zh");
        if (lanPre.equals("zh")) {
            config.locale = Locale.SIMPLIFIED_CHINESE;
        } else {
            config.locale = Locale.ENGLISH;
        }
        Locale.setDefault(config.locale);
        this.getBaseContext().getResources()
                .updateConfiguration(config, resourse.getDisplayMetrics());
    }

    protected void updateConfiguration() {
        Resources resourse = this.getResources();
        Configuration config = resourse.getConfiguration();
        SharedPreferences pre = getSharedPreferences(
                MATApplication.LANGUAGE_PREF, Context.MODE_PRIVATE);
        String lanPre = pre.getString(MATApplication.LANGUAGE_KEY, "zh");
        if (lanPre.equals("zh")) {
            config.locale = Locale.SIMPLIFIED_CHINESE;
        } else {
            config.locale = Locale.ENGLISH;
        }
        Locale.setDefault(config.locale);
        this.getBaseContext().getResources()
                .updateConfiguration(config, resourse.getDisplayMetrics());
    }

    private void queryData(int mType) {
        String mResultTable;
        int id;
        String testItemName ;
        int mResult;
        String mResultString;
        SQLiteDatabase db = mHelper.getWritableDatabase();
        if (mType == ResultDataSave.SINGLE_ITEM_TEST) {
            mResultTable = DatabaseHelper.TABLE_SINGLE_TEST;
        } else if (mType == ResultDataSave.SYSTEM_ITEM_TEST) {
            mResultTable = DatabaseHelper.TABLE_SYSTEM_TEST;
        } else if (mType == ResultDataSave.PCB_ITEM_TEST) {
            mResultTable = DatabaseHelper.TABLE_PCB_TEST;
        } else {
            mResultTable = DatabaseHelper.TABLE_SINGLE_TEST;
        }
        // 查询获得游标
        Cursor cursor = db.query(mResultTable, null, null, null, null, null,
                null);
        Log.d(TAG, "cursor.getCount():" + cursor.getCount());
        // 判断游标是否为空
        for (cursor.moveToFirst(); !cursor.isAfterLast(); cursor.moveToNext()) {
            id = cursor.getInt(0);
            testItemName = cursor.getString(1);
            mResult = cursor.getInt(2);
            mSpanString.append("NUM" + Integer.toString(id) + "  ");
            mSpanString.append(testItemName);
            mSpanString.append("   ");
            if (mResult == ResultDataSave.ITEM_TEST_SUCCES) {
                mResultString = getString(R.string.factorytest_result_succes);
            } else if (mResult == ResultDataSave.ITEM_TEST_FAIL) {
                mResultString = getString(R.string.factorytest_result_fail);
            } else {
                mResultString = getString(R.string.factorytest_result_notest);
            }
            mSpanString.append(mResultString);
            mSpanString.append("\n");
            //Log.d(TAG, "id:" + id + "  username:" + username + "  mResult" + mResult);
        }
        cursor.close();
        db.close();
    }

    private int ReadResultByName(int mType, final String name) {
        int mTestResult;
        mTestResult = mTestResultData.getDataOfList(mType, name);
        return mTestResult;
    }

    private int QueryByName(int mType, final String name) {
        String mResultTable;
        int mTestResult;
        SQLiteDatabase db = mHelper.getWritableDatabase();
        if (mType == ResultDataSave.SINGLE_ITEM_TEST) {
            mResultTable = DatabaseHelper.TABLE_SINGLE_TEST;
        } else if (mType == ResultDataSave.SYSTEM_ITEM_TEST) {
            mResultTable = DatabaseHelper.TABLE_SYSTEM_TEST;
        } else if (mType == ResultDataSave.PCB_ITEM_TEST) {
            mResultTable = DatabaseHelper.TABLE_PCB_TEST;
        } else {
            mResultTable = DatabaseHelper.TABLE_SINGLE_TEST;
        }

        Cursor cursor = db.query(mResultTable, null,
                DatabaseHelper.PROJECTION_NAME + "=?", new String[] { name },
                null, null, null);
        if (cursor == null || cursor.getCount() == 0) { // cur.moveToFirst()
            mTestResult = 0;
        } else {
            cursor.moveToFirst();
            mTestResult = cursor.getInt(2);
        }
        cursor.close();
        db.close();
        return mTestResult;
    }

    @Override
    public void onClick(View v) {
        // TODO Auto-generated method stub
        if (v.getId() == R.id.button_reback) {
            finish();
        } else if (v.getId() == R.id.button_report) {
            ResultDataSave.generateReportFile();
            Toast.makeText(this, "Generate report file success! (Path: /sdcard/Download/all_pass_report.txt)", Toast.LENGTH_SHORT).show();
        }

    }

}
